﻿namespace LockDesktop
{
    using System.Diagnostics;
    using System.Net.Sockets;
    using System.Text;
    using PInvoke;
    using System.Runtime.InteropServices;


    public partial class MainPage : ContentPage
    {

        private const string IP_ADDRESSES_KEY = "RecentIpAddresses";
        private List<string> recentIpAddresses = new List<string>();

        // P/Invoke to get system parameters
        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool SystemParametersInfo(int uAction, int uParam, ref RECT lpvParam, int fuWinIni);

        public MainPage()
        {
            InitializeComponent();
            // 加载存储的 IP 地址
            LoadIpAddresses();
        }

        private async void OnLockClicked(object sender, EventArgs e)
        {
            await SendCommandToServer("lock");
        }

        private async void OnUnlockClicked(object sender, EventArgs e)
        {
            await SendCommandToServer("unlock");
        }

        private async void OnShutdownClicked(object sender, EventArgs e)
        {
            await SendCommandToServer("shutdown");
        }

        private async void OnSnapShotClicked(object sender, EventArgs e)
        {
            await SendCommandToServer("snapshot");
        }

        private void LoadIpAddresses()
        {
            // 从 Preferences 中读取存储的 IP 地址
            string storedIps = Preferences.Get(IP_ADDRESSES_KEY, "");
            if (!string.IsNullOrEmpty(storedIps))
            {
                recentIpAddresses = storedIps.Split(',').ToList();
                // 将存储的 IP 地址添加到 Picker 中
                foreach (var ip in recentIpAddresses)
                {
                    ServerIpPicker.Items.Add(ip);
                }
            }
        }

        private void OnServerIpChanged(object sender, EventArgs e)
        {
            IpInputEditor.Text = ServerIpPicker.SelectedItem.ToString();
        }

        private async void OnSwitchToggled(object sender, ToggledEventArgs e)
        {
            ShutdownTime.IsEnabled = e.Value;
            string time = ShutdownTime.Time.ToString();
            await SendCommandToServer("shutdownplan_"+ e.Value.ToString() + "_" + time);
        }

        private void SaveIpAddresses()
        {
            // 将 IP 地址列表转换为逗号分隔的字符串
            string ipString = string.Join(",", recentIpAddresses);
            // 存储到 Preferences 中
            Preferences.Set(IP_ADDRESSES_KEY, ipString);
        }

        private void AddIpAddress(string ipAddress)
        {
            // 如果列表中已经包含该 IP 地址，先移除
            if (recentIpAddresses.Contains(ipAddress))
            {
                recentIpAddresses.Remove(ipAddress);
            }
            // 将新的 IP 地址添加到列表开头
            recentIpAddresses.Insert(0, ipAddress);
            // 只保留最近 5 次的 IP 地址
            if (recentIpAddresses.Count > 5)
            {
                recentIpAddresses.RemoveAt(5);
            }
            // 清空 Picker 的 Items 集合
            ServerIpPicker.Items.Clear();
            // 将更新后的 IP 地址列表添加到 Picker 的 Items 集合中
            foreach (var ip in recentIpAddresses)
            {
                ServerIpPicker.Items.Add(ip);
            }
            // 保存更新后的 IP 地址列表
            SaveIpAddresses();
        }


        private async Task SendCommandToServer(string command)
        {
            string serverIp = IpInputEditor.Text;
            string serverPortText = ServerPortEntry.Text;

            if (string.IsNullOrWhiteSpace(serverIp) || string.IsNullOrWhiteSpace(serverPortText))
            {
                await DisplayAlert("Error", "Please enter valid server IP and port.", "OK");
                return;
            }

            if (!int.TryParse(serverPortText, out int serverPort))
            {
                await DisplayAlert("Error", "Port must be a number.", "OK");
                return;
            }

            try
            {
                using TcpClient client = new TcpClient();
                await client.ConnectAsync(serverIp, serverPort);

                using NetworkStream stream = client.GetStream();
                byte[] message = Encoding.UTF8.GetBytes(command);
                await stream.WriteAsync(message, 0, message.Length);

                await DisplayAlert("Success", $"Command '{command}' sent successfully!", "OK");

                if (command == "snapshot")
                {
                    // 接收图像长度
                    byte[] lengthBytes = new byte[4];
                    await stream.ReadAsync(lengthBytes, 0, 4);
                    int imageLength = BitConverter.ToInt32(lengthBytes, 0);
                    byte[] imageBytes = new byte[imageLength];
                    await stream.ReadAsync(imageBytes, 0, imageLength);
                    Debug.WriteLine($"Received {imageLength} bytes of image data.");
                    // 将字节数组转换为图像
                    MemoryStream ms = new MemoryStream(imageBytes);
                    //Bitmap bitmap = new Bitmap(ms);
                    // 将图像转换为 ImageSource
                    ImageSource imageSource = ImageSource.FromStream(() => ms);
                    // 显示图像
                    SnapshotImage.Source = imageSource;
                }

                AddIpAddress(serverIp);
            }
            catch (Exception ex)
            {
                await DisplayAlert("Error", $"Failed to send command: {ex.Message}", "OK");
            }
        }
    }

}
